package com.liziguo.lzgfp.system.handler;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.ByteArrayOutputStream;
import java.util.concurrent.TimeUnit;

/**
 * @Author: Liziguo
 * @Date: 2021/12/28 8:39
 */
public class TemporaryStorageHandler extends ChannelInboundHandlerAdapter {

    private final Logger logger = LoggerFactory.getLogger(getClass());

    private ByteArrayOutputStream out = new ByteArrayOutputStream();

    public ByteBuf getByteBuf() {
//        ByteBuf buf = Unpooled.copiedBuffer(out.toByteArray());
//        logger.debug("从临时存储处理器读取字节:{}", buf.readableBytes());
//        logger.debug("从临时存储处理器读取到的内容:{}", buf.toString(StandardCharsets.UTF_8));
//        return buf;
        return Unpooled.copiedBuffer(out.toByteArray());
    }

    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        ctx.channel().eventLoop().schedule(() -> {
            if (ctx.channel().pipeline().get(TemporaryStorageHandler.class) != null) {
//                logger.error("临时存储处理器存在超时(30s)");
                ctx.channel().close();
            }
        }, 30, TimeUnit.SECONDS);
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ByteBuf buf = (ByteBuf) msg;
        byte[] bytes = new byte[buf.readableBytes()];
        buf.readBytes(bytes);
        out.write(bytes);
//        logger.debug("当前所用空间:{}", out.size());
//        logger.trace(new String(out.toByteArray(), StandardCharsets.UTF_8));
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        logger.error(cause.getMessage());
        cause.printStackTrace();
        ctx.close();
    }
}
